<template>
  <div>
    <el-select :style="styles"
               clearable
               :value="value"
               v-bind="$attrs"
               placeholder="请选择计价单位"
               @input="handleInput">
      <el-option v-for="({label, value}, index) in unitOptions"
                 :key="index"
                 :label="label"
                 :value="value">
      </el-option>
    </el-select>
  </div>
</template>

<script>
import {
  WeightUnits,
  QuantityUnits,
  VolumeUnits,
} from "./billing.units.js";

export default {
  name: "BillingUnitSelect",
  inheritAttrs: true,
  props: {
    mode: String,
    value: [],
    styles: {
      type: String,
      default: "width: 100%;"
    }
  },
  data () {
    return {
      QuantityUnits,
      WeightUnits,
      VolumeUnits,
      selectedValue: null,
      lastModeValues: {},
    };
  },
  computed: {
    unitOptions () {
      if ("重量" === this.mode) {
        return this.WeightUnits;
      } else if ("体积" === this.mode) {
        return this.VolumeUnits;
      } else if ("数量" === this.mode) {
        return this.QuantityUnits;
      }
      return [...this.WeightUnits, ...this.VolumeUnits, ...this.QuantityUnits]
    }
  },
  watch: {
    mode (newMode, oldMode) {
      // mode变化后，如果单位不在mode支持的范围，则清空
      const filteredUnit = this.unitOptions.filter(unit => this.value === unit.value)
      if (filteredUnit.length === 0) {
        // TODO: mode还原恢复之前的值
        this.lastModeValues[oldMode] = this.value || this.lastModeValues[oldMode];
        this.selectedValue = this.lastModeValues[newMode];
        this.$emit("input", this.lastModeValues[newMode]);
      }
    }
  },
  methods: {
    handleInput (value) {
      this.selectedValue = value;
      this.$emit("input", value);
    }
  }
};
</script>
